package com.momo.uploadfile;


import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class FileUploadController {


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    @PostMapping("/upload2")
    public void upload(MultipartFile[] files, HttpServletRequest request) {
        //getRealPath是部署到Tomcat服务器上的项目文件夹下的路径，不是源代码的路径
        String realPath = request.getServletContext().getRealPath("/");
        System.out.println(realPath);
        String format = sdf.format(new Date());
        String path = realPath + format;
        File folder = new File(path);
        //如果不存在那么就创建一个文件路径
        if (!folder.exists()) {
            folder.mkdir();
        }
        try {
            //开始便利多文件 上传
            for (MultipartFile file : files) {
                String originalFilename = file.getOriginalFilename();
                String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
                //保存在 同一个文件夹下面
                file.transferTo(new File(folder, fileName));
                //打印文件地址
                String s = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + format + fileName;
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
